package org.zjt.config;

import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.zjt.annotation.RpcService;
import org.zjt.netty.server.NettyServer;
import org.zjt.domain.InvokeBean;
import org.zjt.domain.RegisteNodeData;
import org.zjt.util.JdkProxyFactory;

import java.lang.reflect.Field;

/**
 * DESC
 *
 * @author
 * @create 2017-04-14 下午4:26
 **/
//@Component
public class RpcDiHandler implements   BeanPostProcessor, ApplicationContextAware {
    ApplicationContext applicationContext ;
    JdkProxyFactory jdkProxyFactory = new JdkProxyFactory();

    @Autowired
    ApplicationProperties applicationProperties;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String s) throws BeansException {
       // new NettyServer(applicationProperties.getNettyConfig().getPort());
        try {
            Class<?> clazz = bean.getClass();
            RpcService rpcService = clazz.getAnnotation(RpcService.class);
            if (rpcService != null)
                new NettyServer(applicationProperties.getNettyConfig().getPort());
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                if (! field.isAccessible()) {
                    field.setAccessible(true);
                }
                Reference reference = field.getAnnotation(Reference.class);
                if (reference != null) {
                    //System.setProperty("rpc_customer","1");
                    Object value = refer(reference, field.getType());
                    if (value != null) {
                        field.set(bean, value);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bean;
    }

    private Object refer(Reference reference, Class<?> type) {
       return jdkProxyFactory.getProxy(new InvokeBean(type.getName()),new Class[]{ type });
    }


    @Override
    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        //log.info(o +"     "+ s);
        return o;
    }


}
